<?php

namespace app\model\customer;

use app\model\BaseModel;

/**
 * 客户跟进记录模型
 * 对应数据表：oa_customer_follow
 */
class CustomerFollow extends BaseModel
{
    /**
     * 数据表名
     * @var string
     */
    protected $name = 'customer_follow';

    /**
     * 主键名
     * @var string
     */
    protected $pk = 'id';

    /**
     * 字段类型转换
     * @var array
     */
    protected $type = [
        'id' => 'integer',
        'customer_id' => 'integer',
        'admin_id' => 'integer',
        'content' => 'string',
        'next_time' => 'integer',
        'follow_type' => 'integer',
        'status' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * 可搜索字段
     * @var array
     */
    protected $searchField = ['content'];

    /**
     * 跟进类型
     * @var array
     */
    public const FOLLOW_TYPE = [
        1 => '电话沟通',
        2 => '邮件联系',
        3 => '面谈拜访',
        4 => '微信沟通',
        5 => '其他方式',
    ];

    /**
     * 跟进状态
     * @var array
     */
    public const STATUS = [
        1 => '已跟进',
        2 => '待跟进',
        3 => '已取消',
    ];

    /**
     * 关联客户
     * @return \think\model\relation\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo('app\model\customer\Customer', 'customer_id', 'id');
    }

    /**
     * 关联管理员
     * @return \think\model\relation\BelongsTo
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User', 'admin_id', 'id');
    }

    /**
     * 获取跟进记录列表
     * @param array $params 查询参数
     * @return array
     */
    public function getFollowList($params = [])
    {
        $where = [];
        
        if (!empty($params['customer_id'])) {
            $where[] = ['customer_id', '=', $params['customer_id']];
        }
        
        if (!empty($params['admin_id'])) {
            $where[] = ['admin_id', '=', $params['admin_id']];
        }
        
        if (!empty($params['follow_type'])) {
            $where[] = ['follow_type', '=', $params['follow_type']];
        }
        
        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        return $this->where($where)
            ->with(['customer', 'admin'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1,
            ]);
    }

    /**
     * 获取客户跟进记录
     * @param int $customerId 客户ID
     * @param int $limit 限制数量
     * @return array
     */
    public function getCustomerFollows($customerId, $limit = 10)
    {
        return $this->where('customer_id', $customerId)
            ->with(['admin'])
            ->order('id', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 获取待跟进记录
     * @param int $adminId 管理员ID
     * @return array
     */
    public function getPendingFollows($adminId = null)
    {
        $where = [
            ['status', '=', 2],
            ['next_time', '<=', time() + 86400] // 24小时内
        ];
        
        if ($adminId) {
            $where[] = ['admin_id', '=', $adminId];
        }

        return $this->where($where)
            ->with(['customer', 'admin'])
            ->order('next_time', 'asc')
            ->select()
            ->toArray();
    }

    /**
     * 添加跟进记录
     * @param array $data 跟进数据
     * @return bool
     */
    public function addFollow($data)
    {
        if (empty($data['follow_type'])) {
            $data['follow_type'] = 1;
        }
        
        if (empty($data['status'])) {
            $data['status'] = 1;
        }

        $data['create_time'] = time();
        $data['update_time'] = time();
        
        return $this->save($data);
    }

    /**
     * 更新跟进记录
     * @param int $id 记录ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateFollow($id, $data)
    {
        $data['update_time'] = time();
        
        return $this->where('id', $id)->update($data);
    }

    /**
     * 设置下次跟进时间
     * @param int $id 记录ID
     * @param int $nextTime 下次跟进时间
     * @return bool
     */
    public function setNextFollowTime($id, $nextTime)
    {
        return $this->where('id', $id)->update([
            'next_time' => $nextTime,
            'status' => 2, // 设置为待跟进
            'update_time' => time(),
        ]);
    }

    /**
     * 完成跟进
     * @param int $id 记录ID
     * @param string $content 跟进内容
     * @return bool
     */
    public function completeFollow($id, $content)
    {
        return $this->where('id', $id)->update([
            'content' => $content,
            'status' => 1, // 已跟进
            'update_time' => time(),
        ]);
    }

    /**
     * 获取跟进统计
     * @param int $customerId 客户ID
     * @param int $adminId 管理员ID
     * @return array
     */
    public function getFollowStats($customerId = null, $adminId = null)
    {
        $where = [];
        
        if ($customerId) {
            $where[] = ['customer_id', '=', $customerId];
        }
        
        if ($adminId) {
            $where[] = ['admin_id', '=', $adminId];
        }

        $stats = $this->where($where)
            ->field('follow_type, status, COUNT(*) as count')
            ->group('follow_type, status')
            ->select()
            ->toArray();

        $result = [
            'total' => 0,
            'type_stats' => [],
            'status_stats' => []
        ];

        foreach ($stats as $stat) {
            $result['total'] += $stat['count'];
            
            if (!isset($result['type_stats'][$stat['follow_type']])) {
                $result['type_stats'][$stat['follow_type']] = 0;
            }
            $result['type_stats'][$stat['follow_type']] += $stat['count'];
            
            if (!isset($result['status_stats'][$stat['status']])) {
                $result['status_stats'][$stat['status']] = 0;
            }
            $result['status_stats'][$stat['status']] += $stat['count'];
        }

        return $result;
    }

    /**
     * 删除跟进记录
     * @param int|array $ids 记录ID
     * @return bool
     */
    public function deleteFollow($ids)
    {
        if (is_array($ids)) {
            return $this->where('id', 'in', $ids)->delete();
        } else {
            return $this->where('id', $ids)->delete();
        }
    }

    /**
     * 搜索器：按客户ID搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchCustomerIdAttr($query, $value)
    {
        $query->where('customer_id', $value);
    }

    /**
     * 搜索器：按管理员ID搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchAdminIdAttr($query, $value)
    {
        $query->where('admin_id', $value);
    }

    /**
     * 搜索器：按跟进类型搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchFollowTypeAttr($query, $value)
    {
        $query->where('follow_type', $value);
    }

    /**
     * 搜索器：按状态搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器：按内容搜索
     * @param \think\db\Query $query
     * @param string $value
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }
}